package com.bfdx.testkeyevent.service

import android.accessibilityservice.AccessibilityService
import android.view.KeyEvent
import android.view.accessibility.AccessibilityEvent
import com.bfdx.testkeyevent.toKeyLog
import org.greenrobot.eventbus.EventBus

class KeyEventService : AccessibilityService() {

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        event ?: return
    }

    override fun onInterrupt() {

    }

    override fun onKeyEvent(event: KeyEvent?): Boolean {
        //Logger.w("onKeyEvent=$event")
        event ?: return super.onKeyEvent(event)
        //坑：不能直接传递KeyEvent，在传递过程中可能会变化，导致接收时，已经不是发送时的状态(另外KeyEvent没有实现hashCode)。
        postToBus(event.toKeyLog())
        return super.onKeyEvent(event)
    }

    private fun postToBus(event: Any) = EventBus.getDefault().post(event)

}